package beautiful.butterfly.drds.data_exchange.transport.record.column.column_cast;

import beautiful.butterfly.drds.data_exchange.exception.CommonErrorCode;
import beautiful.butterfly.drds.data_exchange.exception.DataExchangeException;
import beautiful.butterfly.drds.data_exchange.transport.record.column.DateColumn;
import beautiful.butterfly.drds.data_exchange.util.Configuration;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.util.TimeZone;

/**
 * 后续为了可维护性，可以考虑直接使用 apache 的DateFormatUtils.
 * <p>
 * 迟南已经修复了该问题，但是为了维护性，还是直接使用apache的内置函数
 */
class DateCast
{

    static String datetimeFormat = "yyyy-MM-dd HH:mm:ss";

    static String dateFormat = "yyyy-MM-dd";

    static String timeFormat = "HH:mm:ss";

    static String timeZone = "GMT+8";

    static TimeZone timeZoner = TimeZone.getTimeZone(DateCast.timeZone);

    static void init(final Configuration configuration)
    {
        DateCast.datetimeFormat = configuration.getString(
                "common.table_column_name_list.datetimeFormat", datetimeFormat);
        DateCast.timeFormat = configuration.getString(
                "common.table_column_name_list.timeFormat", timeFormat);
        DateCast.dateFormat = configuration.getString(
                "common.table_column_name_list.dateFormat", dateFormat);
        DateCast.timeZone = configuration.getString("common.table_column_name_list.timeZone",
                DateCast.timeZone);
        DateCast.timeZoner = TimeZone.getTimeZone(DateCast.timeZone);
        return;
    }

    static String asString(final DateColumn column)
    {
        if (null == column.asDate())
        {
            return null;
        }

        switch (column.getDateType())
        {
            case DATE:
                return DateFormatUtils.format(column.asDate(), DateCast.dateFormat,
                        DateCast.timeZoner);
            case TIME:
                return DateFormatUtils.format(column.asDate(), DateCast.timeFormat,
                        DateCast.timeZoner);
            case DATETIME:
                return DateFormatUtils.format(column.asDate(),
                        DateCast.datetimeFormat, DateCast.timeZoner);
            default:
                throw DataExchangeException
                        .asDataExchangeException(CommonErrorCode.CONVERT_NOT_SUPPORT,
                                "时间类型出现不支持类型，目前仅支持DATE/TIME/DATETIME。该类型属于编程错误，请反馈给DataX开发团队 .");
        }
    }
}
